package com.lyr.query.dynamic.core.schema;

import com.lyr.query.dynamic.core.domain.DynamicQueryProperties;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Objects;
import javax.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

/**
 * 动态条件sql Schema 初始化
 *
 * @author zk
 **/
@Slf4j
public class SchemaInitializer {
    /**
     * 表名
     */
    private static final String TABLE_NAME = "query_config";
    /**
     * 配置
     */
    private final DynamicQueryProperties properties;
    //    @Resource
    private final SqlSessionFactory sqlSessionFactory;

    public SchemaInitializer(DynamicQueryProperties dynamicQueryProperties, SqlSessionFactory sqlSessionFactory) {
        this.properties = dynamicQueryProperties;
        this.sqlSessionFactory = sqlSessionFactory;
    }

    /**
     * 创建表
     */
    private static void createTable(Connection connection) throws SQLException {
        // 2. 创建表（兼容 MySQL 5.7/8.0）
        String ddl =
            "CREATE TABLE `" + SchemaInitializer.TABLE_NAME + "` (" + "  `id` bigint NOT NULL AUTO_INCREMENT COMMENT '主键'," + "  `user_id` bigint DEFAULT NULL COMMENT '用户id',"
                + "  `conditions_json` varchar(500) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT '[]' COMMENT '查询条件',"
                + "  `create_time` datetime DEFAULT NULL COMMENT '创建时间',"
                + "  `tenant_id` bigint DEFAULT NULL COMMENT '租户id',"
                + "  `path` varchar(500) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci COMMENT '接口路径',"
                + "  `update_time` datetime DEFAULT NULL COMMENT '更新时间'," + "  PRIMARY KEY (`id`)" + ") ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;";

        try (Statement stmt = connection.createStatement()) {
            stmt.execute(ddl);
            log.info("表 {} 创建成功", SchemaInitializer.TABLE_NAME);
        }
    }

    @PostConstruct
    public void init() {
        // 如果配置了不保存查询条件，则不创建表
        if (Objects.isNull(properties.getSaveConfig()) || Boolean.FALSE.equals(properties.getSaveConfig().getEnable())) {
            return;
        }
        try (SqlSession session = sqlSessionFactory.openSession()) {
            Connection connection = session.getConnection();
            // 1. 检查表是否存在
            boolean tableExists = checkTableExists(connection);
            // 2. 如果表不存在,则直接创建表
            if (!tableExists) {
                createTable(connection);
            } else if (Boolean.TRUE.equals(properties.getSaveConfig().getReCreateTable())) {
                //  表存在，或需要重建，则重新创建
                try (Statement stmt = connection.createStatement()) {
                    stmt.execute("DROP TABLE IF EXISTS " + TABLE_NAME);
                    createTable(connection);
                }
            }
        } catch (SQLException e) {
            log.error("表初始化失败", e);
        }
    }

    /**
     * 检查表是否存在
     */
    private boolean checkTableExists(Connection connection) throws SQLException {
        String sql = "SELECT COUNT(*) FROM information_schema.tables " + "WHERE table_schema = DATABASE() AND table_name = ?";
        try (PreparedStatement pstmt = connection.prepareStatement(sql)) {
            pstmt.setString(1, SchemaInitializer.TABLE_NAME);
            try (ResultSet rs = pstmt.executeQuery()) {
                if (rs.next()) {
                    return rs.getInt(1) > 0;
                }
            }
        }
        return false;
    }
}